package com.mangatta.ec2.activity;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.mangatta.cloud.dao.InstanceDetailDao;
import com.mangatta.cloud.ec2.Ec2Instance;
import com.mangatta.ec2.adaptor.InstanceListAdaptor;
import com.mangatta.ec2.adaptor.InstanceView;
import com.mangatta.ec2.monitor.InstanceListMonitor;
import com.mangatta.ec2.util.Util;

public class InstanceListActivity extends ListActivity {
    private final static String TAG = InstanceListActivity.class.getSimpleName();

    private InstanceDetailDao instanceDetailDao;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.instance_list);
        instanceDetailDao = new InstanceDetailDao(this);
        Log.d(TAG, "onCreated");
    }

    private List<Ec2Instance> getEC2Instances(){
        List<Ec2Instance> instances = instanceDetailDao.getInstances();
        Log.d(TAG, "Fetech instances of size:"+instances.size());
        return instances;
    }
    
    @Override
	protected void onStart() {
		super.onStart();
		if(!Util.isAWSCredentialsAvailable(this)){
			getListView().removeAllViewsInLayout();
			Toast.makeText(this, "Please set your AWS Credentails first.", Toast.LENGTH_SHORT);
		}
	}


    
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
		setListAdapter(new InstanceListAdaptor(this, getEC2Instances()));
	}


	@Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroyed");
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    	Intent alarmViewIntent = new Intent(this, AlarmConfigurationListActivity.class);
    	InstanceView view = (InstanceView) v.getTag();
		alarmViewIntent.putExtra( Util.INSTANCE_ID, view.instanceId.getText().toString() );
		startActivity(alarmViewIntent);
    
    }
    
    public void onRefreshInstanceClick(View button){
    	   InstanceListMonitor monitor = new InstanceListMonitor(Util.getAWSCredentails(this));
    	   List<Ec2Instance> instances = monitor.getInstancesDetail();
    	   Log.d(TAG, "Refresh Fetech instances of size:"+instances.size());
    	   instanceDetailDao.persistInstanceDetail(instances);
           InstanceListAdaptor adapter = (InstanceListAdaptor) getListAdapter();
           adapter.setEc2Instances(instances);
           adapter.notifyDataSetChanged();
           getListView().refreshDrawableState();
    }
}
